package com.link.base.base.product.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.common.model.Attachment;
import com.link.base.base.common.model.Image;
import com.link.base.base.common.model.InterObject;
import com.link.base.base.common.service.AttachmentService;
import com.link.base.base.interprodgroup.model.Interprodgroup;
import com.link.base.base.interprodgroup.service.InterprodgroupService;
import com.link.base.base.invloc.model.Invloc;
import com.link.base.base.invloc.service.InvlocService;
import com.link.base.base.orgnization.model.Orgnization;
import com.link.base.base.orgnization.service.OrgnizationService;
import com.link.base.base.product.dao.mybatis.mapper.ProductMapper;
import com.link.base.base.product.model.PriceListItem;
import com.link.base.base.product.model.Product;
import com.link.base.base.product.service.ProductService;
import com.link.base.basic.model.ListOfValue;
import com.link.base.basic.service.BasicCommonService;
import com.link.base.enterprise.model.CoreEnterprise;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.interceptor.SecurityInterceptor;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.query.Sorter;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.ServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.util.AppConstants;
import com.link.core.util.QueryParamUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author /product/
 * @date unknown
 * @comments 产品操作请求处理
 */
@Controller
@RequestMapping("/link/product")
public class ProductController extends BasicController<Product> {

    @Resource
    private ProductService productService;
    @Resource
    private AccountService accountService;
    @Resource
    private OrgnizationService orgnizationService;

    @Resource
    private InterprodgroupService interprodgroupService;

    @Resource
    private BasicCommonService basicCommonService;
    /**
     * 附件
     */
    @Resource
    private AttachmentService attachmentService;

    @Resource
    private InvlocService invlocService;
    @Resource
    private ProductMapper productMapper;

    @Override
    public BasicService<Product> getBasicService() throws Exception {
        return productService;
    }

    /**
     * 新增或修改之前做的操作
     */
    @Override
    public void beforUpsert(Product record, HttpServletRequest request) throws Exception {
        record.setProdSeriesLovType(AppConstants.PROD_SERIES);
        record.setProdStatusLovType(AppConstants.PROD_STATUS);
        record.setRetreatFlagLovType(AppConstants.S_IF);
        if (null == record.getProdVolume()) {
            record.setProdVolume(0.0);
        }
    }

    @RequestMapping(value = "/queryGoodsByExamplePage")
    @ResponseBody
    public Map<String, Object> queryGoodsByExamplePage(@JsonParam QueryParams qps, @JsonParam Product entity, HttpSession session,
                                                       HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.preDealSecurity(request);
            Product t = (Product) BasicModel.transformClass(entity.getClass(), qps);
            beforQueryAllOrExample(t, request);
            beforQueryExample(t, request);
            //设置查询商品信息
            t.setProdGoodType("Good");
            List<Product> list = getBasicService().queryByExamplePage(t);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", getCount((BasicModel) t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Product>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    @ResponseBody
    public void uploadImg(Product record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> myfiles = multipartRequest.getFiles("myfiles");
        try {
            // 上传图片到服务器
            List<Image> list = productService.imgUpload(myfiles);
            // 将图片写到数据库
            productService.productImageUpate(record, list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            OutputStream os;
            response.setContentType("text/html;charset=UTF-8");
            os = response.getOutputStream();
            JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(os);
            jsonGenerator.writeObject(result);
        } catch (IOException e) {
            LCLogger.withException(e);
        }
    }

    @RequestMapping(value = "/prodModelUpdate", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> prodModelUpdate(InterObject record, QueryParams qps, HttpSession session, HttpServletRequest request,
                                               HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        Product pd = new Product();
        pd.setId(record.getPreObjId());
        pd.setProdModelId(record.getRearObjId());
        try {
            productService.prodModelUpdate(pd);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 更新产品的详细信息
     */
    @RequestMapping(value = "/prodDetailsUpdate", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> prodDetailsUpdate(@JsonParam Product record, HttpSession session,
                                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            productService.prodDetailsUpdate(record);
            /*Product newEntry = productService.queryById(record);
            result.put("newRow", newEntry);*/
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 经销商平台的商品列表
     */
    @RequestMapping(value = "/queryPartnerProdPage")
    @ResponseBody
    public Map<String, Object> partnerProdList(@JsonParam QueryParams qps, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            String venderEmpType = "VendorEmployee";
            boolean isVender = StringUtils.equals(UserUtil.getUser().getEmpType(), venderEmpType);
            Product t = isVender ? this.getVendorProdListQbs(qps, session, request, response)
                    : this.getpartnerProdListQbs(qps, session, request, response);
            List<Product> list = productService.queryProdWithAcctPricePage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount((BasicModel) t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Product>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询有产品的品牌和系列值列表
     */
    @RequestMapping(value = "/queryBrandList")
    @ResponseBody
    public Map<String, Object> queryBrandList(QueryParams qps, HttpSession session,
                                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Product t = this.getpartnerProdListQbs(qps, session,
                    request, response);
            t.setPageFlag(false);
            List<ListOfValue> list = productService.queryBrandList(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount((BasicModel) t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<ListOfValue>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    public Product getpartnerProdListQbs(QueryParams qps, HttpSession session,
                                         HttpServletRequest request, HttpServletResponse response) throws Exception {
        CoreUser user = UserUtil.getUser();
        Long acctId = user.getAcctId();
        if (acctId == null) {
            throw new ServiceException("ACCT-014");
        }
        Product t = (Product) BasicModel.transformClass(Product.class, qps);
        t.setAcctId(acctId);
        String from = request.getParameter("from");
        String saleOrder = "saleOrder";
        //如果是创建销售订单查询产品
        if (saleOrder.equals(from)) {
            Long orgId = acctId;
            //校验组织
            Orgnization org = orgnizationService.queryById(orgId);
            if (org == null) {
                throw new ServiceException("PRODUCT-011");
            }
            Long priceListId = org.getPriceListId();
            if (priceListId == null) {
                t.setxAttr03(priceListId);
            } else {
                throw new ServiceException("PRODUCT-012");
            }

        }
        if (StringUtils.isNotBlank(qps.getAttr4())) {
            List<Long> tagIdList = new ArrayList<>();
            try {
                List<String> stringList = JSON.parseArray(qps.getAttr4(), String.class);
                stringList.forEach(item -> tagIdList.add(Long.parseLong(item)));
            } catch (Exception e) {
                throw new ServiceException("PRODUCT-031");
            }
            t.setIds(tagIdList);
        }

        //判断是否为多价格表
        //Enterprise enterprise = (Enterprise)session.getAttribute("UserEnterpriseContext");
        CoreEnterprise enterprise = SecurityInterceptor.tempEnterpirse.get();
        String multiPriceList = enterprise.getIsMultiPriceList();
        t.setAttr7(multiPriceList);
        return t;

    }

    /**
     * 品牌商查询某经销商的产品列表，attr1：为品牌商需要查询的经销商Id,
     * 当品牌商做导入操作，进行校验是，产品prodCode的校验会调用这个方法
     * 此时无acctId，则改为用QPS中的filterRow传入acctCode，再去查询acctId
     *
     * @author NingLanhao
     * @date 2018-11-29 19:05
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return com.link.business.base.product.model.Product
     */
    public Product getVendorProdListQbs(QueryParams qps, HttpSession session,
                                        HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 前端传入attr1：为品牌商需要查询的经销商Id
        String acctId = qps.getAttr1();
        if (StringUtils.isBlank(acctId)) {
            // 无客户ID时，通过客户编码查询获得ID
            JSONArray array = JSONObject.parseArray(qps.getFiltersRaw());
            int accntCodeIndex = 1;
            String valueKey = "value";
            String acctCode = ((JSONObject) array.get(accntCodeIndex)).get(valueKey).toString();
            Account acctQuery = (Account) QueryParamUtil.addQpsFilter(Account.class,
                    new Filter("acctCode", acctCode));
            List<Account> accounts = accountService.queryByExamplePage(acctQuery);
            if (CollectionUtils.isEmpty(accounts)) {
                throw new ServiceException("PRODUCT-032");
            }
            acctId = String.valueOf(accounts.get(0).getId());
        }
        Product t = (Product) BasicModel.transformClass(Product.class, qps);
        t.setAcctId(Long.parseLong(acctId));
        //判断是否为多价格表
        CoreEnterprise enterprise = SecurityInterceptor.tempEnterpirse.get();
        String multiPriceList = enterprise.getIsMultiPriceList();
        t.setAttr7(multiPriceList);
        return t;
    }

    /**
     * 门店平台的商品列表
     */
    @RequestMapping(value = "/queryPartnerProductPage")
    @ResponseBody
    public Map<String, Object> partnerProductList(@JsonParam QueryParams qps, HttpSession session, HttpServletRequest request,
                                                  HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            Long acctId = user.getAcctId();
            if (acctId == null) {
                throw new ServiceException("ACCT-014");
            }
            Account account = new Account();
            account.setId(acctId);
            account = accountService.queryById(account);
            Product t = (Product) BasicModel.transformClass(Product.class, qps);
            // t.setAcctId(acctId);
            t.setOrgId(account.getOrgId());
            if (StringUtils.isNotBlank(qps.getAttr4())) {
                List<Long> tagIdList = new ArrayList<Long>();
                String[] tagIds = qps.getAttr4().split(",");
                for (String tagid : tagIds) {
                    tagIdList.add(Long.parseLong(tagid));
                }
                t.setIds(tagIdList);
            }

            // 判断是否为多价格表
            // Enterprise enterprise =
            // (Enterprise)session.getAttribute("UserEnterpriseContext");
            CoreEnterprise enterprise = SecurityInterceptor.tempEnterpirse.get();
            String multiPriceList = enterprise.getIsMultiPriceList();
            t.setAttr7(multiPriceList);

            List<Product> list = productService.queryProductWithAcctPricePage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount((BasicModel) t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Product>());
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * 查询一条记录
     */
    @RequestMapping(value = "/queryAcctProdById")
    @ResponseBody
    public Map<String, Object> queryAcctProdById(@JsonParam Product entity, HttpSession session,
                                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            entity.setAcctId(UserUtil.getUser().getAcctId());

            //判断是否为多价格表
//          Enterprise enterprise = (Enterprise)session.getAttribute("UserEnterpriseContext");
            CoreEnterprise enterprise = SecurityInterceptor.tempEnterpirse.get();
            String multiPriceList = enterprise.getIsMultiPriceList();
            entity.setAttr7(multiPriceList);

            Product record = productService.queryProdWithAcctPriceById(entity);
            List<Product> list = new ArrayList<Product>();
            list.add(record);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("result", record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 根据促销政策头ID查询符合符合条件的产品
     * 促销政策头ID(attr1)
     */
    @RequestMapping(value = "/queryProdByPcyId")
    @ResponseBody
    public Map<String, Object> queryProdByPcyId(QueryParams qps, HttpSession session,
                                                HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            Long acctId = user.getAcctId();
            if (acctId == null) {
                throw new ServiceException("ACCT-014");
            }
            Product t = (Product) BasicModel.transformClass(Product.class, qps);
            t.setAcctId(acctId);

            //判断是否为多价格表
//          Enterprise enterprise = (Enterprise)session.getAttribute("UserEnterpriseContext");
            CoreEnterprise enterprise = SecurityInterceptor.tempEnterpirse.get();
            String multiPriceList = enterprise.getIsMultiPriceList();
            t.setAttr7(multiPriceList);

            List<Product> list = productService.queryProdWithAcctPriceByPcyId(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询现场赠品可选择的产品
     * @author 秦学刚
     * @param interprodgroup
     * @return
     * @throws Exception 异常信息
     */

    @RequestMapping(value = "/queryCouponProd")
    @ResponseBody
    public Map<String, Object> queryCouponProd(@JsonParam QueryParams qps, @JsonParam Interprodgroup interprodgroup, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();
        try {
            CoreUser user = UserUtil.getUser();
            Orgnization orgnization = new Orgnization();
            orgnization.setOrgType("BranchCompany");
            orgnization.setId(user.getOrgId());
            orgnization.setUpOrDown("UP");
            List<Orgnization> list = orgnizationService.queryTierOrgnization(orgnization);
            if (list == null || list.size() <= 0) {
                result.put("rows", new ArrayList<>());
                result.put("total", 0);
            } else {
                qps.addFilter(new Filter("companyId", Filter.OP_EQUAL, String.valueOf(list.get(0).getId())));
                qps.addFilter(new Filter("groupType", Filter.OP_EQUAL, "Reward"));
                qps.addFilter(new Filter("prodIsEffective", Filter.OP_EQUAL, "Y"));
                interprodgroup = (Interprodgroup) BasicModel.transformClass(interprodgroup, qps);
                List<Interprodgroup> interprodgroups = interprodgroupService.queryByExamplePage(interprodgroup);
                result.put("rows", interprodgroups);
                if (interprodgroups != null && interprodgroups.size() < qps.getRows()) {
                    result.put("total", interprodgroups.size());
                } else if (interprodgroups != null && interprodgroups.size() == qps.getRows()) {
                    result.put("total", interprodgroups.size() + 1);
                }
            }
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询产品二级及二级以下分类
     */
    @RequestMapping(value = "/queryProdCategory")
    @ResponseBody
    public List<ListOfValue> queryProdCategory(Long parentId, String parentVal, String cateType,
                                               HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryProdCategory")
                .withMessage("加载地址信息...").flush();
        List<ListOfValue> list = null;
        try {
            QueryParams qps = new QueryParams();
            qps.addSorter(new Sorter("seq", "ASC"));
            qps.setPageFlag(false);
            ListOfValue t = (ListOfValue) BasicModel.transformClass(ListOfValue.class, qps);
            t.setParentId(parentId);
            t.setParentVal(parentVal);
            t.setType(cateType);
            list = basicCommonService.queryByExamplePage(t);
        } catch (Exception e) {
            LCLogger.withException(e);
            list = new ArrayList<ListOfValue>();
        }
        return list;
    }

    /**
     * 创建订单时选产品，产品MVG窗口中未选择的产品列表
     */
    @RequestMapping(value = "/prodOrderlist")
    @ResponseBody
    public Map<String, Object> prodOrderlist(QueryParams qps, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.preDealSecurity(request);
            if (StringUtils.isBlank(qps.getAttr1())) {
                qps.setAttr1("noMatchId");
            }
            Product t = (Product) BasicModel.transformClass(Product.class, qps);
            List<Product> list = productService.queryProdOrderlistPage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/queryUnSelectedInPriceListDetailPage")
    @ResponseBody
    public Map<String, Object> queryUnSelectedInPriceListDetailPage(@JsonParam QueryParams qps, @JsonParam PriceListItem entity, HttpSession session,
                                                                    HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.preDealSecurity(request);
            PriceListItem t = (PriceListItem) BasicModel.transformClass(entity.getClass(), qps);
            /*beforQueryAllOrExample(t,request);
            beforQueryExample(t,request);*/
            t.setHeadId(Long.parseLong(request.getParameter("headId")));
            System.out.println("headId----:" + t.getHeadId());
            List<Product> list = ((ProductService) getBasicService()).queryUnSelectedInPriceListDetailPage(t);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", getCount((BasicModel) t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<PriceListItem>());
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * 查询经销商销售商品
     */
    @RequestMapping(value = "/queryUnSelectedInDealerPriceListPage")
    @ResponseBody
    public Map<String, Object> queryUnSelectedInDealerPriceListPage(@JsonParam QueryParams qps, @JsonParam Product entity, HttpSession session,
                                                                    HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Long acctId = UserUtil.getUser().getAcctId();
            if (acctId == null) {
                throw new ServiceException("PRODUCT-010");
            }
            qps.preDealSecurity(request);
            Product example = (Product) BasicModel.transformClass(entity, qps);
            example.setAcctId(acctId);
            List<Product> list = productService.queryUnSelectedInDealerPriceListPage(example);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", getCount(example, list.size()));
        } catch (BasicServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<PriceListItem>());
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<PriceListItem>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/queryUnSelectedInPurchasePlanListPage")
    @ResponseBody
    public Map<String, Object> queryUnSelectedInPurchasePlanListPage(@JsonParam QueryParams qps, @JsonParam Product entity, HttpSession session,
                                                                     HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Long acctId = entity.getAcctId();
            // DMS系统从后台获取acctId
            if (acctId == null) {
                acctId = UserUtil.getUser().getAcctId();
                if (acctId == null) {
                    throw new ServiceException("PRODUCT-010");
                }
            }
            qps.preDealSecurity(request);
            Product example = (Product) BasicModel.transformClass(entity, qps);
            example.setAcctId(acctId);
            List<Product> list = productService.queryUnSelectedInPurchasePlanListPage(example);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", getCount(example, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<PriceListItem>());
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * HuangLJ 通过产品Id查询产品图片
     *
     * @param entity   产品实体
     * @param session  session
     * @param request  请求
     * @param response 相应
     * @return 返回Map
     */
    @RequestMapping(value = "/queryProductPicByProdId")
    @ResponseBody
    public Map<String, Object> queryProductPicByProdId(@RequestBody Product entity, HttpSession session,
                                                       HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<Attachment> attachmentList = productService.queryProductPicByProdId(entity);

            result.put("success", true);
            result.put("rows", attachmentList);
            result.put("total", attachmentList.size());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/updateProdMainImgId")
    @ResponseBody
    public Map<String, Object> updateProdMainImgId(@RequestBody Product product, HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse respons) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Image image = new Image();
            image.setId(product.getProdImgId());
            List<Image> imageList = new ArrayList<Image>();
            imageList.add(image);

            productService.productImageUpate(product, imageList);
            result.put("success", true);

        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * 查询价格表下面的产品，包含价格信息
     *
     * @param qps
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/queryProductByPriceHeadId")
    @ResponseBody
    public Map<String, Object> queryProductByPriceHeadId(@JsonParam QueryParams qps, @JsonParam PriceListItem entity, HttpSession session,
                                                         HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.preDealSecurity(request);
            PriceListItem t = (PriceListItem) BasicModel.transformClass(entity.getClass(), qps);
            t.setHeadId(Long.parseLong(request.getParameter("headId")));
            /*库存管理-库存盘点-添加产品，显示当时库存量START*/
            String num = "num";
            if (num.equals(qps.getAttr1())) {
                CoreUser user = UserUtil.getUser();
                Invloc invlocParam = new Invloc();
                invlocParam.setOwnerId(user.getAcctId());
                List<Invloc> invlocList = invlocService.queryByAcctId(invlocParam);
                t.setInvlocId(invlocList.get(0).getId());
            }
            /*库存管理-库存盘点-添加产品，显示当时库存量END*/
            List<Product> list = ((ProductService) getBasicService()).queryProductByPriceHeadId(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
        }
        return result;
    }


    @RequestMapping(value = "/queryById")
    @ResponseBody
    @Override
    public Map<String, Object> queryById(@JsonParam Product entity, HttpSession session,
                                         HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            entity.setLoginCorpId(user.getLoginCorpId());
            Product record = productService.queryProdById(entity);
            List<Product> list = new ArrayList<Product>();
            list.add(record);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("result", record);
            result.put("success", true);
        } catch (BasicServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 新建或更新一条记录
     */
    @RequestMapping(value = "/upsertProd")
    @ResponseBody
    public Map<String, Object> upsertProd(@RequestBody Product entity, HttpSession session,
                                          HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            beforUpsert(entity, request);
            checkData(entity, request);
            String base = "base";
            if (!getBasicService().isInsertFlag(entity) && !checkExistDataCache(base, session, entity)) {
                throw new ServiceException("PUBLIC-002");
            }
            CoreUser user = UserUtil.getUser();
            entity.setCorpid(user.getLoginCorpId());
            productService.prodUpsert(entity);
            //getBasicService().upsert(entity);
            Product newEntry = productService.queryProdById(entity);
            result.put("newRow", newEntry);
            result.put("success", true);
        } catch (BasicServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 删除一条记录
     */
    @Override
    @RequestMapping(value = "/deleteById")
    @ResponseBody
    public Map<String, Object> deleteById(@JsonParam Product entity, HttpSession session,
                                          HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("deleteById")
                .withMessage("删除一条列表信息...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            beforDelete(entity, request);
            checkData(entity, request);
            String base = "base";
            if (!checkExistDataCache(base, session, entity)) {
                throw new ServiceException("PUBLIC-031");
            }

            CoreUser user = UserUtil.getUser();
            entity.setLoginCorpId(user.getLoginCorpId());
            productService.deleteProdAndTagById(entity);
            result.put("success", true);
        } catch (BasicServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * 查询不同类别产品的第一条 by lizt 20170703
     */
    @RequestMapping(value = "/queryProductByType")
    @ResponseBody
    public Map<String, Object> queryProductByType(Product entity, HttpSession session, HttpServletRequest request,
                                                  HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<Product> list = productService.queryProductByType(entity);
            result.put("success", true);
            result.put("result", list);

        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }


    /**
     * 按照创建时间,查询维护了二级系列的产品的第一条数据
     *
     * @author : LiQun
     * @date : 上午9:21 2018/9/18
     */
    @RequestMapping(value = "/queryProdSecSeries")
    @ResponseBody
    public Map<String, Object> queryProdSecSeries(Product produc, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryProdSecSeries")
                .withMessage("按照创建时间,查询维护了二级系列的产品的第一条数据,用于筛选.").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Map<String, List<Product>> prodSecSeries = productService.queryProdSecSeries(produc);
            result.put("success", true);
            result.put("result", prodSecSeries);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }


    /**
     * 生成分享二维码
     *
     * @author lujiang
     */
    @RequestMapping(value = "/createMiniprogramCode")
    @ResponseBody
    public Map<String, Object> createMiniprogramCode(@RequestBody Product product, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        try {
            map = productService.createMiniprogramCode(product);
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", e.getMessage());
            e.getMessage();
        }
        return map;
    }


    /**
     * 查询分类下有产品的一级分类
     *
     * @author KuangRuifeng
     */
    @RequestMapping(value = "/queryHasProdMatSeries")
    @ResponseBody
    public Map<String, Object> queryHasProdMatSeries(Product produc, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryHasProdMatSeries")
                .withMessage("查询分类下有产品的一级分类.").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<Product> res = productService.queryHasProdMatSeries(produc);
            result.put("success", true);
            result.put("result", res);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 查询小程序商品详情
     *
     * @author lujiang
     */
    @RequestMapping(value = "/queryByProdId")
    @ResponseBody
    public Map<String, Object> queryByProdId(@JsonParam Product product) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            result = productService.queryByProdId(product);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 重写queryByExamplePage
     *
     * @param qps
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     * @author lujiang
     */
    @Override
    @RequestMapping(value = "/queryByExamplePage")
    @ResponseBody
    public Map<String, Object> queryByExamplePage(@JsonParam QueryParams qps, @JsonParam Product entity,
                                                  HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        HashMap result = new HashMap();
        try {
            qps.preDealSecurity(request);
            Product temp = (Product) BasicModel.transformClass(entity, qps);
            this.beforQueryAllOrExample(temp, request);
            this.beforQueryExample(temp, request);
            Boolean totalFlag = temp.getTotalFlag();
            //小程序
            String loginType = "MP";
            if (loginType.equals(entity.getLoginType())) {
                temp.setTotalFlag(false);
            }
            List<Product> list = this.getBasicService().queryByExamplePage(temp);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            //小程序逻辑
            if (true == totalFlag && loginType.equals(entity.getLoginType())) {
                temp.setTotalFlag(true);
                temp.setAttr6(null);
                temp.setAttr7(null);
                temp.setOnlyCountFlag(true);
                List<Product> productList = this.getBasicService().queryByExamplePage(temp);
                Integer listTotal = 0;
                if (productList.size() > 0) {
                    listTotal = productList.get(0).getTotal();
                }
                result.put("total", listTotal);
            } else {
                result.put("total", getCount(temp, list.size()));
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", e.getMessage());
            LCLogger.withException(e);
        }

        return result;
    }

    /**
     * 查询小程序排序前9的三级系列
     *
     * @author KuangRuifeng
     * @date 2018年11月1日
     */
    @RequestMapping(value = "/queryHotThdSeries")
    @ResponseBody
    public Map<String, Object> queryHotThdSeries(Product produc, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();
        try {
            result.put("rows", productService.queryHotThdSeries(produc));
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }


    /**
     * 查询分享产品一条记录
     *
     * @author 唐健
     * @date 2018/11/19
     */
    @RequestMapping(value = "/queryShareProdById")
    @ResponseBody
    public Map<String, Object> queryShareProdById(@JsonParam Product entity, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Product record = productService.queryByIdForShare(entity);
            Attachment a = new Attachment();
            a.setHeadId(entity.getId());
            a.setPageFlag(false);
            List<Attachment> attList = attachmentService.queryByExamplePage(a);
            record.setAnonymousFlag("Y");
            for (Attachment att : attList) {
                att.setAnonymousFlag("Y");
            }
            result.put("result", record);
            result.put("attList", attList);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 新建小程序产品
     *
     * @param product
     * @return
     * @throws Exception 异常信息
     * @author wangdawei
     */
    @RequestMapping(value = "/newMpProd")
    @ResponseBody
    public Map<String, Object> newMpProd(@RequestBody Product product) {
        Map<String, Object> result = new HashMap<>();
        try {
            result = productService.newMpProd(product);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", e.getMessage());
            LCLogger.withException(e);

        }
        return result;
    }

    /**
     * 编辑小程序产品
     *
     * @param product
     * @return
     * @throws Exception 异常信息
     * @author wangdawei
     */
    @RequestMapping(value = "/getMpProdInfo")
    @ResponseBody
    public Map<String, Object> getMpProdInfo(Product product) {
        Map<String, Object> result = new HashMap<>();
        try {
            result = productService.getMpProdInfo(product);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 编辑小程序产品
     *
     * @param product
     * @return
     * @throws Exception 异常信息
     * @author wangdawei
     */
    @RequestMapping(value = "/updateMpProd")
    @ResponseBody
    public Map<String, Object> updateMpProd(@RequestBody Product product) {
        Map<String, Object> result = new HashMap<>();
        try {
            result = productService.updateMpProd(product);
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 校验产品编码
     *
     * @param prodCode 产品编码
     * @return 查询结果
     * @throws Exception 异常信息
     * @author wangdawei
     * @date 2019/1/10
     */
    @RequestMapping(value = "/checkProdCode")
    @ResponseBody
    public Map<String, Object> checkProdCode(String prodCode) {
        Map<String, Object> result = new HashMap<>();
        try {
            Boolean flag = productService.checkProdCode(prodCode);
            result.put("success", true);
            result.put("flag", flag);
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 根据组织ID 获取价格表然后获取价格表下的产品
     *
     * @param entity
     * @param qps
     * @return Map
     * @author 黄正杨
     * @date 2019/4/23
     */
    @RequestMapping({"/queryByOrgIdPage"})
    @ResponseBody
    public Map<String, Object> queryByOrgIdPage(@JsonParam QueryParams qps, @JsonParam Product entity,
                                                HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            qps.preDealSecurity(request);
            if (entity.getQueryOrgId() == null) {
                result.put("success", false);
                result.put("rows", new ArrayList());
                result.put("result", "未获取到该商机的所属门店信息");
                result.put("code", "400");
                return result;
            }
            Orgnization orgnization = orgnizationService.queryById(entity.getQueryOrgId());
            if (null == orgnization || orgnization.getPriceListId() == null) {
                result.put("success", false);
                result.put("rows", new ArrayList());
                result.put("result", "该门店未维护价格表");
                result.put("code", "400");
                return result;
            }
            qps.addFilter(new Filter("priceListId", Filter.OP_EQUAL, String.valueOf(orgnization.getPriceListId())));
            Product temp = BasicModel.transformClass(entity, qps);
            List<Product> list = productService.queryByOrgIdPage(entity);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(temp, list.size()));
            result.put("code", "200");
        } catch (BasicServiceException e) {
            result.put("success", false);
            result.put("rows", new ArrayList());
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
            result.put("code", e.getCode());
        } catch (Exception e) {
            result.put("success", false);
            result.put("rows", new ArrayList());
            result.put("result", e.getMessage());
            result.put("code", "400");
        }
        return result;
    }

    /**
     * 查销量(小程序调用)
     *
     * @param qps
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     * @author wangdawei
     */
    @RequestMapping(value = "/queryCumulateByExamplePage")
    @ResponseBody
    public Map<String, Object> queryCumulateByExamplePage(@JsonParam QueryParams qps, @JsonParam Product entity,
                                                          HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        HashMap result = new HashMap();
        try {
            qps.preDealSecurity(request);
            qps.setPageFlag(true);
            qps.addFilter(new Filter("integralMallVisible", "integralMallVisible", Filter.OP_EQUAL, "Y"));
            qps.addFilter(new Filter("priceListId", "priceListId", Filter.OP_EQUAL,
                    UserUtil.getUser().getPriceListId().toString()));
            qps.addSorter(new Sorter("cumulateSale", Sorter.DIR_DESC));
            qps.setRows(4);
            entity.setPage(1);
            entity.setRows(4);
            entity.setStartRow(1);
            entity.setEndRow(4);
            Product temp = (Product) BasicModel.transformClass(entity, qps);
            List<Product> list = productMapper.queryByExamplePage(temp);
            result.put("success", true);
            result.put("rows", list);
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", e.getMessage());
            LCLogger.withException(e);
        }

        return result;
    }

    /**
     * 从门店迁移根据物流追溯码查询产品功能
     * @author 姚江漪
     * @date 2019/08/14 16:49
     */
    @RequestMapping(value = "/queryProductByLogCode")
    @ResponseBody
    public Map<String, Object> queryProductByLogCode(@RequestBody Product product) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            // 物流码
            if (StringUtils.isNotBlank(product.getProdBarcode())) {
                Map<String, Object> queryResult = productService.queryProductByLogCode(product);
                result.put("success", true);
                result.put("result", queryResult);
            } else {
                result.put("success", false);
                result.put("result", "未获取到物流码，请检查！");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 手工录入产品条形码
     * @author 姚江漪
     * @date 2019/08/14 16:49
     */
    @RequestMapping(value = "/queryProductByManual")
    @ResponseBody
    public Map<String, Object> queryProductByManual(@RequestBody Product product) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            // 物流码不能为空
            if (StringUtils.isNotBlank(product.getProdBarcode())) {
                Product resultProd = productService.queryProductByManual(product);
                result.put("success", true);
                result.put("result", resultProd);
            } else {
                result.put("success", false);
                result.put("result", "请输入必输信息！");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

}

